package com.example.elmmerchants.Shop_Activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.Image;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.bumptech.glide.load.model.FileLoader;
import com.example.elmmerchants.Product_Management.Create_Product_Page;
import com.example.elmmerchants.Product_Management.Shop_Management_Page;
import com.example.elmmerchants.Product_Management.Sort_Page;
import com.example.elmmerchants.R;
import com.example.elmmerchants.SQL.Connection_SQL;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLOutput;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Discount_Product_Page extends AppCompatActivity {

    LinearLayout choose_product, set_product_card_view, set_start_date, set_end_date, create_data;
    CardView last_view;
    View last_left_view;
    TextView how_many_date, start_date, end_date, is_all_custom, is_just_new_custom;
    Switch is_auto_postponement, is_just_in_open_shop_use;
    CheckBox is_read_and_accept;

    boolean is_loading_category_data = false, is_just_new_custom_can_use = false, is_finish_upload = false;
    ArrayList<String> category = new ArrayList<>();
    String email, start_date_text = "", end_date_text = "";
    HashMap<String, Integer> choose_which_category = new HashMap<>();
    List<List<String>> product_data = new ArrayList<>();
    List<byte[]> product_pic = new ArrayList<>();
    AlertDialog dialog;
    List<View_List> viewList = new ArrayList<>();
    int which_list = 0, choose_how_many_product_to_batch = 0;
    HashMap<TextView, CheckBox> choose_which_product_map = new HashMap<>();
    HashMap<String, Integer> getChoose_which_product = new HashMap<>();
    String choose_which_purchase_limit_in_order = "不限购";
    String choose_which_purchase_limit_in_inventory = "不限量";
    List<Choose_Which_Product_In_Discount_Page> product_data_in_choose = new ArrayList();
    long start_date_second = 0;
    String all_product_name = "";
    String all_product_data = "";

    private class Category_Data_Thread extends Thread {

        LinearLayout set_category_layout, product_list_layout;
        ScrollView set_category_list_view, product_list_view;

        public Category_Data_Thread(LinearLayout set_category_layout, LinearLayout product_list_layout, ScrollView set_category_list_view, ScrollView product_list_view) {
            this.set_category_layout = set_category_layout;
            this.product_list_layout = product_list_layout;
            this.set_category_list_view = set_category_list_view;
            this.product_list_view = product_list_view;
        }

        @Override
        public void run() {
            product_data.clear();
            product_pic.clear();
            category.clear();
            viewList.clear();
            which_list = 0;
            is_loading_category_data = false;

            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "SELECT * FROM merchant WHERE email = ?;";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, email);
                    ResultSet set = preparedStatement.executeQuery();
                    while (set.next()) {
                        String category_temp = "";
                        for (int i = 0; i < set.getString("shop_category").length(); i++) {
                            if (set.getString("shop_category").charAt(i) != ',') {
                                category_temp += set.getString("shop_category").charAt(i);
                            }
                            else {
                                if (!category_temp.equals("全部")) {
                                    category.add(category_temp);
                                }
                                category_temp = "";
                            }
                        }
                    }

                    String sql2 = "SELECT * FROM `" + email + "_merchant_product`;";
                    preparedStatement = connection.prepareStatement(sql2);
                    ResultSet set2 = preparedStatement.executeQuery();
                    while (set2.next()) {
                        List<String> product = new ArrayList<>();
                        product.add(set2.getString("name"));
                        product.add(set2.getString("category_1"));
                        product.add(set2.getString("category_2"));
                        product.add(set2.getString("category_3"));
                        product.add(set2.getString("category_4"));
                        product.add(set2.getString("category_5"));
                        product_pic.add(set2.getBytes("picture"));
                        product.add(String.valueOf(set2.getDouble("product_price")));

                        getChoose_which_product.put(set2.getString("name"), 0);
                        product_data.add(product);
                    }
                    is_loading_category_data = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_loading_category_data) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    set_category_layout.removeAllViews();
                    product_list_layout.removeAllViews();
                    for (int i = 0; i < category.size(); i++) {
                        View_List view_list = new View_List();
                        choose_which_category.put(category.get(i), 0);
                        View view2 = LayoutInflater.from(Discount_Product_Page.this).inflate(R.layout.set_category_layout_to_add_discount_page_product_view, null);
                        TextView category_in_product_name = view2.findViewById(R.id.category_in_product_name);
                        category_in_product_name.setText(category.get(i));
                        LinearLayout product = view2.findViewById(R.id.product);
                        for (int j = 0; j < product_data.size(); j++) {
                            if (product_data.get(j).get(1).equals(category.get(i)) || product_data.get(j).get(2).equals(category.get(i)) || product_data.get(j).get(3).equals(category.get(i)) || product_data.get(j).get(4).equals(category.get(i)) || product_data.get(j).get(5).equals(category.get(i))) {
                                View view3 = LayoutInflater.from(Discount_Product_Page.this).inflate(R.layout.set_choose_discount_page_product_card_view, null);

                                ImageView product_pic_image = view3.findViewById(R.id.product_pic);
                                Bitmap decodedImage = BitmapFactory.decodeByteArray(product_pic.get(j), 0, product_pic.get(j).length);
                                product_pic_image.setImageBitmap(decodedImage);

                                TextView product_name = view3.findViewById(R.id.product_name);
                                product_name.setText(product_data.get(j).get(0));

                                TextView product_price = view3.findViewById(R.id.product_price);
                                product_price.setText(product_data.get(j).get(6));

                                CheckBox choose_which_product = view3.findViewById(R.id.choose_which_product);
                                int finalJ = j;
                                choose_which_product.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        if (choose_which_product.isChecked()) {
                                            for (TextView key : choose_which_product_map.keySet()) {
                                                if (key.getText().toString().equals(product_name.getText().toString())) {
                                                    choose_which_product_map.get(key).setChecked(true);
                                                    getChoose_which_product.replace(product_data.get(finalJ).get(0), 1);

                                                }
                                            }
                                        }
                                        else {
                                            for (TextView key : choose_which_product_map.keySet()) {
                                                if (key.getText().toString().equals(product_name.getText().toString())) {
                                                    choose_which_product_map.get(key).setChecked(false);
                                                    getChoose_which_product.replace(product_data.get(finalJ).get(0), 0);
                                                }
                                            }
                                        }
                                    }
                                });

                                choose_which_product_map.put(product_name, choose_which_product);
                                product.addView(view3);
                            }
                        }
                        product_list_layout.addView(view2);
                        view_list.view = view2;
                        View view = LayoutInflater.from(Discount_Product_Page.this).inflate(R.layout.category_item_view, null);
                        CardView item = view.findViewById(R.id.item);
                        View left_view = view.findViewById(R.id.left_view);
                        TextView item_name = view.findViewById(R.id.item_name);
                        item_name.setText(category.get(i));
                        item_name.setPadding(0, 30, 0, 30);
                        view_list.cardView = item;
                        view_list.left_view = left_view;
                        if (i == 0) {
                            item.setBackgroundColor(Color.rgb(245, 246, 251));
                            left_view.setVisibility(View.VISIBLE);
                            last_view = item;
                            last_left_view = left_view;
                            product_list_view.smoothScrollTo(0, 0);
                        }
                        item.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                product_list_view.smoothScrollTo(0, (int) view2.getY());
                            }
                        });
                        product_list_view.setOnScrollChangeListener(new View.OnScrollChangeListener() {
                            @Override
                            public void onScrollChange(View view, int i, int i1, int i2, int i3) {
                                if (which_list + 1 < viewList.size() && viewList.get(which_list).view.getY() < i1 && viewList.get(which_list + 1).view.getY() <= i1) {
                                    viewList.get(which_list + 1).cardView.setBackgroundColor(Color.rgb(245, 246, 251));
                                    viewList.get(which_list + 1).left_view.setVisibility(View.VISIBLE);
                                    last_view.setBackgroundColor(Color.WHITE);
                                    last_left_view.setVisibility(View.GONE);
                                    last_view = viewList.get(which_list + 1).cardView;
                                    last_left_view = viewList.get(which_list + 1).left_view;
                                    which_list += 1;
                                }
                                else if (which_list > 0 && viewList.get(which_list).view.getY() > i1 && viewList.get(which_list - 1).view.getY() <= i1) {
                                    viewList.get(which_list - 1).cardView.setBackgroundColor(Color.rgb(245, 246, 251));
                                    viewList.get(which_list - 1).left_view.setVisibility(View.VISIBLE);
                                    last_view.setBackgroundColor(Color.WHITE);
                                    last_left_view.setVisibility(View.GONE);
                                    last_view = viewList.get(which_list - 1).cardView;
                                    last_left_view = viewList.get(which_list - 1).left_view;
                                    which_list -= 1;
                                }
                            }
                        });
                        viewList.add(view_list);
                        set_category_layout.addView(view);
                    }
                }
            });
        }
    }

    private class Show_Product_To_Set_Discount_Thread extends Thread {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    set_product_card_view.removeAllViews();
                    for (int i = 0; i < product_data_in_choose.size(); i++) {
                        View view = LayoutInflater.from(Discount_Product_Page.this).inflate(R.layout.set_discount_product_card_view, null);

                        ImageView product_pic = view.findViewById(R.id.product_pic);
                        Bitmap decodedImage = BitmapFactory.decodeByteArray(product_data_in_choose.get(i).product_pic, 0, product_data_in_choose.get(i).product_pic.length);
                        product_pic.setImageBitmap(decodedImage);

                        TextView is_choose_order_purchase_limit = view.findViewById(R.id.is_choose_order_purchase_limit);
                        TextView is_choose_inventory_purchase_limit = view.findViewById(R.id.is_choose_inventory_purchase_limit);

                        if (product_data_in_choose.get(i).is_purchase_limit_in_order) {
                            is_choose_order_purchase_limit.setText("限购" + product_data_in_choose.get(i).set_order_purchase_limit);
                        }

                        if (product_data_in_choose.get(i).is_purchase_limit_in_inventory) {
                            is_choose_inventory_purchase_limit.setText("限量" + product_data_in_choose.get(i).set_inventory_purchase_limit);
                        }

                        TextView product_name = view.findViewById(R.id.product_name);
                        product_name.setText(product_data_in_choose.get(i).product_name);

                        TextView this_product_how_much = view.findViewById(R.id.this_product_how_much);
                        this_product_how_much.setText(product_data_in_choose.get(i).product_price);

                        TextView how_many_discount = view.findViewById(R.id.how_many_discount);

                        EditText after_discount_money = view.findViewById(R.id.after_discount_money);
                        if (product_data_in_choose.get(i).after_discount_money != null) {
                            after_discount_money.setText(product_data_in_choose.get(i).after_discount_money.getText().toString());
                            if (!after_discount_money.getText().toString().isEmpty() && Double.parseDouble(after_discount_money.getText().toString()) < Double.parseDouble(product_data_in_choose.get(i).product_price)) {
                                double discount = Double.parseDouble(after_discount_money.getText().toString()) / Double.parseDouble(product_data_in_choose.get(i).product_price) * 10;
                                how_many_discount.setText(String.format("%.2f", discount) + "折");
                            }
                            else {
                                how_many_discount.setText("");
                            }
                        }
                        product_data_in_choose.get(i).after_discount_money = after_discount_money;
                        int finalI = i;
                        after_discount_money.addTextChangedListener(new TextWatcher() {
                            @Override
                            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                            }

                            @Override
                            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                            }

                            @Override
                            public void afterTextChanged(Editable editable) {
                                if (!after_discount_money.getText().toString().isEmpty() && Double.parseDouble(after_discount_money.getText().toString()) < Double.parseDouble(product_data_in_choose.get(finalI).product_price)) {
                                    double discount = Double.parseDouble(after_discount_money.getText().toString()) / Double.parseDouble(product_data_in_choose.get(finalI).product_price) * 10;
                                    how_many_discount.setText(String.format("%.2f", discount) + "折");
                                }
                                else {
                                    how_many_discount.setText("");
                                }
                            }
                        });

                        LinearLayout set_purchase_limit = view.findViewById(R.id.set_purchase_limit);
                        set_purchase_limit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                choose_which_purchase_limit_in_order = "不限购";
                                choose_which_purchase_limit_in_inventory = "不限量";

                                Dialog dialog1 = new Dialog(view.getContext());
                                dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
                                dialog1.setContentView(R.layout.set_purchase_limit_in_discount_page);

                                EditText set_order_purchase_limit = dialog1.findViewById(R.id.set_order_purchase_limit);
                                EditText set_inventory_purchase_limit = dialog1.findViewById(R.id.set_inventory_purchase_limit);

                                RadioGroup click_what_in_order = dialog1.findViewById(R.id.click_what_in_order);
                                RadioButton choose_order_purchase_limit = dialog1.findViewById(R.id.choose_order_purchase_limit);
                                LinearLayout is_choose_order_purchase_limit_layout = dialog1.findViewById(R.id.is_choose_order_purchase_limit);

                                click_what_in_order.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                                    @Override
                                    public void onCheckedChanged(RadioGroup radioGroup, int i) {
                                        RadioButton type = findViewById(radioGroup.getCheckedRadioButtonId());
                                        if (radioGroup.getCheckedRadioButtonId() == choose_order_purchase_limit.getId()) {
                                            is_choose_order_purchase_limit_layout.setVisibility(View.VISIBLE);
                                            choose_which_purchase_limit_in_order = "限购";
                                        }
                                        else {
                                            is_choose_order_purchase_limit_layout.setVisibility(View.GONE);
                                            choose_which_purchase_limit_in_order = "不限购";
                                        }
                                    }
                                });

                                RadioGroup click_what_in_inventory = dialog1.findViewById(R.id.click_what_in_inventory);
                                RadioButton choose_inventory_purchase_limit = dialog1.findViewById(R.id.choose_inventory_purchase_limit);
                                LinearLayout is_choose_inventory_purchase_limit_layout = dialog1.findViewById(R.id.is_choose_inventory_purchase_limit);

                                click_what_in_inventory.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                                    @Override
                                    public void onCheckedChanged(RadioGroup radioGroup, int i) {
                                        RadioButton type = findViewById(radioGroup.getCheckedRadioButtonId());
                                        if (radioGroup.getCheckedRadioButtonId() == choose_inventory_purchase_limit.getId()) {
                                            is_choose_inventory_purchase_limit_layout.setVisibility(View.VISIBLE);
                                            choose_which_purchase_limit_in_inventory = "限量";
                                        }
                                        else {
                                            is_choose_inventory_purchase_limit_layout.setVisibility(View.GONE);
                                            choose_which_purchase_limit_in_inventory = "不限量";
                                        }
                                    }
                                });

                                LinearLayout cancel_button = dialog1.findViewById(R.id.cancel_button);
                                cancel_button.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        dialog1.dismiss();
                                    }
                                });

                                LinearLayout current = dialog1.findViewById(R.id.current);
                                current.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        if (choose_which_purchase_limit_in_order.equals("限购")) {
                                            product_data_in_choose.get(finalI).is_purchase_limit_in_order = true;
                                            product_data_in_choose.get(finalI).set_order_purchase_limit = Integer.parseInt(set_order_purchase_limit.getText().toString());
                                        }
                                        else {
                                            product_data_in_choose.get(finalI).is_purchase_limit_in_order = false;
                                            product_data_in_choose.get(finalI).set_order_purchase_limit = 0;
                                        }
                                        if (choose_which_purchase_limit_in_inventory.equals("限量")) {
                                            product_data_in_choose.get(finalI).is_purchase_limit_in_inventory = true;
                                            product_data_in_choose.get(finalI).set_inventory_purchase_limit = Integer.parseInt(set_inventory_purchase_limit.getText().toString());
                                        }
                                        else {
                                            product_data_in_choose.get(finalI).is_purchase_limit_in_inventory = false;
                                            product_data_in_choose.get(finalI).set_inventory_purchase_limit = 0;
                                        }

                                        if (product_data_in_choose.get(finalI).is_purchase_limit_in_order) {
                                            is_choose_order_purchase_limit.setText("限购" + product_data_in_choose.get(finalI).set_order_purchase_limit);
                                        }

                                        if (product_data_in_choose.get(finalI).is_purchase_limit_in_inventory) {
                                            is_choose_inventory_purchase_limit.setText("限量" + product_data_in_choose.get(finalI).set_inventory_purchase_limit);
                                        }
                                        dialog1.dismiss();
                                    }
                                });

                                dialog1.show();
                                dialog1.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                                dialog1.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                                dialog1.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
                                dialog1.getWindow().setGravity(Gravity.BOTTOM);
                            }
                        });

                        ImageView delete = view.findViewById(R.id.delete);
                        delete.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view1) {
                                set_product_card_view.removeView(view);
                                for (int j = 0; j < product_data_in_choose.size(); j++) {
                                    if (product_data_in_choose.get(j).product_name.equals(product_name.getText().toString())) {
                                        product_data_in_choose.remove(j);
                                        break;
                                    }
                                }
                            }
                        });

                        set_product_card_view.addView(view);
                    }
                }
            });
        }
    }

    private class Upload_Data_Thread extends Thread {
        @Override
        public void run() {
            is_finish_upload = false;

            for (int i = 0; i < product_data_in_choose.size(); i++) {
                all_product_name += product_data_in_choose.get(i).product_name;
                all_product_name += ",";
                all_product_data += product_data_in_choose.get(i).after_discount_money.getText().toString();
                all_product_data += ",";
                if (product_data_in_choose.get(i).is_purchase_limit_in_order) {
                    all_product_data += "1";
                    all_product_data += ",";
                }
                else {
                    all_product_data += "0";
                    all_product_data += ",";
                }
                if (product_data_in_choose.get(i).is_purchase_limit_in_inventory) {
                    all_product_data += "1";
                    all_product_data += ",";
                }
                else {
                    all_product_data += "0";
                    all_product_data += ",";
                }
                all_product_data += product_data_in_choose.get(i).set_order_purchase_limit;
                all_product_data += ",";
                all_product_data += product_data_in_choose.get(i).set_inventory_purchase_limit;
                all_product_data += ",";
                all_product_data += "所有折扣数据已添加";
                all_product_data += ",";
            }

            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "insert into `elm`.`merchant_discount_product_page` (email, activity_start_day, activity_end_day, is_auto_postponement, is_just_in_open_shop_use, all_product_name, all_product_data, is_just_new_custom) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, email);
                    preparedStatement.setString(2, start_date_text);
                    preparedStatement.setString(3, end_date_text);
                    if (is_auto_postponement.isChecked()) {
                        preparedStatement.setInt(4, 1);
                    }
                    else {
                        preparedStatement.setInt(4, 0);
                    }

                    if (is_just_in_open_shop_use.isChecked()) {
                        preparedStatement.setInt(5, 1);
                    }
                    else {
                        preparedStatement.setInt(5, 0);
                    }

                    preparedStatement.setString(6, all_product_name);
                    preparedStatement.setString(7, all_product_data);
                    if (is_just_new_custom_can_use) {
                        preparedStatement.setInt(8, 1);
                    }
                    else {
                        preparedStatement.setInt(8, 0);
                    }
                    preparedStatement.executeUpdate();
                    is_finish_upload = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_finish_upload) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dialog.dismiss();
                    Intent intent = new Intent(Discount_Product_Page.this, Check_All_Activity_Page.class);
                    setResult(1, intent);
                    finish();
                }
            });
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_discount_product_page);

        email = getIntent().getStringExtra("email");

        choose_product = findViewById(R.id.choose_product);
        set_product_card_view = findViewById(R.id.set_product_card_view);
        set_start_date = findViewById(R.id.set_start_date);
        set_end_date = findViewById(R.id.set_end_date);
        how_many_date = findViewById(R.id.how_many_date);
        start_date = findViewById(R.id.start_date);
        end_date = findViewById(R.id.end_date);
        is_auto_postponement = findViewById(R.id.is_auto_postponement);
        is_just_in_open_shop_use = findViewById(R.id.is_just_in_open_shop_use);
        is_all_custom = findViewById(R.id.is_all_custom);
        is_just_new_custom = findViewById(R.id.is_just_new_custom);
        is_read_and_accept = findViewById(R.id.is_read_and_accept);
        create_data = findViewById(R.id.create_data);

        choose_product.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Dialog dialog1 = new Dialog(view.getContext());
                dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
                dialog1.setContentView(R.layout.set_choose_discount_page_card_view);

                LinearLayout set_category_layout = dialog1.findViewById(R.id.set_category_layout);
                LinearLayout product_list_layout = dialog1.findViewById(R.id.product_list_layout);
                ScrollView product_list_view = dialog1.findViewById(R.id.product_list_view);
                ScrollView set_category_list_view = dialog1.findViewById(R.id.set_category_list_view);
                set_category_layout.addView(LayoutInflater.from(view.getContext()).inflate(R.layout.load_data, null));
                product_list_layout.addView(LayoutInflater.from(view.getContext()).inflate(R.layout.load_data, null));
                Category_Data_Thread categoryDataThread = new Category_Data_Thread(set_category_layout, product_list_layout, set_category_list_view, product_list_view);
                categoryDataThread.start();
                LinearLayout batch_setting_discount = dialog1.findViewById(R.id.batch_setting_discount);
                batch_setting_discount.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        boolean can_go_to_set = false;
                        for (String key : getChoose_which_product.keySet()) {
                            if (getChoose_which_product.get(key) == 1) {
                                can_go_to_set = true;
                                choose_how_many_product_to_batch += 1;
                            }
                        }

                        if (can_go_to_set) {
                            dialog1.dismiss();
                            Dialog dialog1 = new Dialog(view.getContext());
                            dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
                            dialog1.setContentView(R.layout.set_batch_setting_card_view_in_discount_page);

                            EditText after_discount_money = dialog1.findViewById(R.id.after_discount_money);
                            EditText set_order_purchase_limit = dialog1.findViewById(R.id.set_order_purchase_limit);
                            EditText set_inventory_purchase_limit = dialog1.findViewById(R.id.set_inventory_purchase_limit);

                            ImageView close = dialog1.findViewById(R.id.close);
                            close.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    dialog1.dismiss();
                                }
                            });

                            LinearLayout cancel_button = dialog1.findViewById(R.id.cancel_button);
                            cancel_button.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    dialog1.dismiss();
                                }
                            });

                            TextView choose_how_many_product = dialog1.findViewById(R.id.choose_how_many_product);
                            choose_how_many_product.setText("" + choose_how_many_product_to_batch);

                            RadioGroup click_what_in_order = dialog1.findViewById(R.id.click_what_in_order);
                            RadioButton choose_order_purchase_limit = dialog1.findViewById(R.id.choose_order_purchase_limit);
                            LinearLayout is_choose_order_purchase_limit = dialog1.findViewById(R.id.is_choose_order_purchase_limit);

                            click_what_in_order.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                                @Override
                                public void onCheckedChanged(RadioGroup radioGroup, int i) {
                                    RadioButton type = findViewById(radioGroup.getCheckedRadioButtonId());
                                    if (radioGroup.getCheckedRadioButtonId() == choose_order_purchase_limit.getId()) {
                                        is_choose_order_purchase_limit.setVisibility(View.VISIBLE);
                                        choose_which_purchase_limit_in_order = "限购";
                                    }
                                    else {
                                        is_choose_order_purchase_limit.setVisibility(View.GONE);
                                        choose_which_purchase_limit_in_order = "不限购";
                                    }
                                }
                            });

                            RadioGroup click_what_in_inventory = dialog1.findViewById(R.id.click_what_in_inventory);
                            RadioButton choose_inventory_purchase_limit = dialog1.findViewById(R.id.choose_inventory_purchase_limit);
                            LinearLayout is_choose_inventory_purchase_limit = dialog1.findViewById(R.id.is_choose_inventory_purchase_limit);

                            click_what_in_inventory.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                                @Override
                                public void onCheckedChanged(RadioGroup radioGroup, int i) {
                                    RadioButton type = findViewById(radioGroup.getCheckedRadioButtonId());
                                    if (radioGroup.getCheckedRadioButtonId() == choose_inventory_purchase_limit.getId()) {
                                        is_choose_inventory_purchase_limit.setVisibility(View.VISIBLE);
                                        choose_which_purchase_limit_in_inventory = "限量";
                                    }
                                    else {
                                        is_choose_inventory_purchase_limit.setVisibility(View.GONE);
                                        choose_which_purchase_limit_in_inventory = "不限量";
                                    }
                                }
                            });

                            LinearLayout current = dialog1.findViewById(R.id.current);
                            current.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if (after_discount_money.getText().toString().isEmpty() || (choose_which_purchase_limit_in_order.equals("限购") && set_order_purchase_limit.getText().toString().isEmpty()) || (choose_which_purchase_limit_in_inventory.equals("限购") && set_inventory_purchase_limit.getText().toString().isEmpty())) {
                                        Toast.makeText(Discount_Product_Page.this, "请输入所有资料", Toast.LENGTH_SHORT).show();
                                    }
                                    else {
                                        for (String key : getChoose_which_product.keySet()) {
                                            if (getChoose_which_product.get(key) == 1) {
                                                boolean is_in_product_data = false;
                                                Choose_Which_Product_In_Discount_Page chooseWhichProductInDiscountPage = new Choose_Which_Product_In_Discount_Page();
                                                for (int i = 0; i < product_data_in_choose.size(); i++) {
                                                    if (product_data_in_choose.get(i).product_name.equals(key)) {
                                                        product_data_in_choose.get(i).after_discount_money = after_discount_money;
                                                        if (choose_which_purchase_limit_in_order.equals("限购")) {
                                                            product_data_in_choose.get(i).is_purchase_limit_in_order = true;
                                                            product_data_in_choose.get(i).set_order_purchase_limit = Integer.parseInt(set_order_purchase_limit.getText().toString());
                                                        }
                                                        else {
                                                            product_data_in_choose.get(i).is_purchase_limit_in_order = false;
                                                            product_data_in_choose.get(i).set_order_purchase_limit = 0;
                                                        }
                                                        if (choose_which_purchase_limit_in_inventory.equals("限量")) {
                                                            product_data_in_choose.get(i).is_purchase_limit_in_inventory = true;
                                                            product_data_in_choose.get(i).set_inventory_purchase_limit = Integer.parseInt(set_inventory_purchase_limit.getText().toString());
                                                        }
                                                        else {
                                                            product_data_in_choose.get(i).is_purchase_limit_in_inventory = false;
                                                            product_data_in_choose.get(i).set_inventory_purchase_limit = 0;
                                                        }
                                                        is_in_product_data = true;
                                                        break;
                                                    }
                                                }
                                                if (!is_in_product_data) {
                                                    for (int i = 0; i < product_data.size(); i++) {
                                                        if (product_data.get(i).get(0).equals(key)) {
                                                            chooseWhichProductInDiscountPage.product_pic = product_pic.get(i);
                                                            chooseWhichProductInDiscountPage.product_price = product_data.get(i).get(6);
                                                            break;
                                                        }
                                                    }
                                                    chooseWhichProductInDiscountPage.product_name = key;
                                                    chooseWhichProductInDiscountPage.after_discount_money = after_discount_money;
                                                    if (choose_which_purchase_limit_in_order.equals("限购")) {
                                                        chooseWhichProductInDiscountPage.is_purchase_limit_in_order = true;
                                                        chooseWhichProductInDiscountPage.set_order_purchase_limit = Integer.parseInt(set_order_purchase_limit.getText().toString());
                                                    }
                                                    else {
                                                        chooseWhichProductInDiscountPage.is_purchase_limit_in_order = false;
                                                        chooseWhichProductInDiscountPage.set_order_purchase_limit = 0;
                                                    }
                                                    if (choose_which_purchase_limit_in_inventory.equals("限量")) {
                                                        chooseWhichProductInDiscountPage.is_purchase_limit_in_inventory = true;
                                                        chooseWhichProductInDiscountPage.set_inventory_purchase_limit = Integer.parseInt(set_inventory_purchase_limit.getText().toString());
                                                    }
                                                    else {
                                                        chooseWhichProductInDiscountPage.is_purchase_limit_in_inventory = false;
                                                        chooseWhichProductInDiscountPage.set_inventory_purchase_limit = 0;
                                                    }
                                                    product_data_in_choose.add(chooseWhichProductInDiscountPage);
                                                }
                                            }
                                        }
                                        dialog1.dismiss();
                                        Show_Product_To_Set_Discount_Thread showProductToSetDiscountThread = new Show_Product_To_Set_Discount_Thread();
                                        showProductToSetDiscountThread.start();
                                    }
                                }
                            });

                            dialog1.show();
                            dialog1.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                            dialog1.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                            dialog1.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
                            dialog1.getWindow().setGravity(Gravity.BOTTOM);
                        }
                        else {
                            Toast.makeText(Discount_Product_Page.this, "请选择商品", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

                LinearLayout one_by_one_setting_discount = dialog1.findViewById(R.id.one_by_one_setting_discount);
                one_by_one_setting_discount.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        for (String key : getChoose_which_product.keySet()) {
                            if (getChoose_which_product.get(key) == 1) {
                                boolean is_in_product_data = false;
                                Choose_Which_Product_In_Discount_Page chooseWhichProductInDiscountPage = new Choose_Which_Product_In_Discount_Page();
                                for (int i = 0; i < product_data_in_choose.size(); i++) {
                                    if (product_data_in_choose.get(i).product_name.equals(key)) {
                                        product_data_in_choose.get(i).after_discount_money = null;
                                        product_data_in_choose.get(i).is_purchase_limit_in_order = false;
                                        product_data_in_choose.get(i).set_order_purchase_limit = 0;
                                        product_data_in_choose.get(i).is_purchase_limit_in_inventory = false;
                                        product_data_in_choose.get(i).set_inventory_purchase_limit = 0;
                                        is_in_product_data = true;
                                        break;
                                    }
                                }
                                if (!is_in_product_data) {
                                    for (int i = 0; i < product_data.size(); i++) {
                                        if (product_data.get(i).get(0).equals(key)) {
                                            chooseWhichProductInDiscountPage.product_pic = product_pic.get(i);
                                            chooseWhichProductInDiscountPage.product_price = product_data.get(i).get(6);
                                            break;
                                        }
                                    }
                                    chooseWhichProductInDiscountPage.product_name = key;
                                    chooseWhichProductInDiscountPage.after_discount_money = null;
                                    chooseWhichProductInDiscountPage.is_purchase_limit_in_order = false;
                                    chooseWhichProductInDiscountPage.set_order_purchase_limit = 0;
                                    chooseWhichProductInDiscountPage.is_purchase_limit_in_inventory = false;
                                    chooseWhichProductInDiscountPage.set_inventory_purchase_limit = 0;
                                    product_data_in_choose.add(chooseWhichProductInDiscountPage);
                                }
                            }
                        }
                        dialog1.dismiss();
                        Show_Product_To_Set_Discount_Thread showProductToSetDiscountThread = new Show_Product_To_Set_Discount_Thread();
                        showProductToSetDiscountThread.start();
                    }
                });

                dialog1.show();
                dialog1.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                dialog1.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                dialog1.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
                dialog1.getWindow().setGravity(Gravity.BOTTOM);
            }
        });

        set_start_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Dialog dialog1 = new Dialog(view.getContext());
                dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
                dialog1.setContentView(R.layout.set_activity_date);

                DatePicker set_date = dialog1.findViewById(R.id.set_date);
                set_date.setMinDate(System.currentTimeMillis() - 1000);

                TextView save = dialog1.findViewById(R.id.save);
                save.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        start_date_text = "";
                        end_date_text = "";
                        how_many_date.setText("0天");
                        end_date.setText("请选择日期");
                        if (set_date.getMonth() + 1 < 10 && set_date.getDayOfMonth() < 10) {
                            start_date_text += set_date.getYear() + "/" + "0" + (set_date.getMonth() + 1) + "/" + "0" + set_date.getDayOfMonth();
                        }
                        else if (set_date.getMonth() + 1 < 10) {
                            start_date_text += set_date.getYear() + "/" + "0" + (set_date.getMonth() + 1) + "/" + set_date.getDayOfMonth();
                        }
                        else if (set_date.getDayOfMonth() < 10) {
                            start_date_text += set_date.getYear() + "/" + (set_date.getMonth() + 1) + "/" + "0" + set_date.getDayOfMonth();
                        }
                        else {
                            start_date_text += set_date.getYear() + "/" + (set_date.getMonth() + 1) + "/" + set_date.getDayOfMonth();
                        }
                        start_date.setText(start_date_text);
                        dialog1.dismiss();
                    }
                });

                dialog1.show();
                dialog1.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, 1500);
                dialog1.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                dialog1.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
                dialog1.getWindow().setGravity(Gravity.BOTTOM);
            }
        });

        set_end_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (start_date_text.isEmpty()) {
                    Toast.makeText(Discount_Product_Page.this, "请设置起始日期", Toast.LENGTH_SHORT).show();
                }
                else {
                    Dialog dialog1 = new Dialog(view.getContext());
                    dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
                    dialog1.setContentView(R.layout.set_activity_date);

                    DatePicker set_date = dialog1.findViewById(R.id.set_date);
                    DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
                    String temp = start_date_text;
                    try {
                        Date date = df.parse(temp);
                        start_date_second = date.getTime();
                        set_date.setMinDate(start_date_second + 86400000);
                    } catch (ParseException e) {
                        throw new RuntimeException(e);
                    }

                    TextView save = dialog1.findViewById(R.id.save);
                    save.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            end_date_text = "";
                            if (set_date.getMonth() + 1 < 10 && set_date.getDayOfMonth() < 10) {
                                end_date_text += set_date.getYear() + "/" + "0" + (set_date.getMonth() + 1) + "/" + "0" + set_date.getDayOfMonth();
                            }
                            else if (set_date.getMonth() + 1 < 10) {
                                end_date_text += set_date.getYear() + "/" + "0" + (set_date.getMonth() + 1) + "/" + set_date.getDayOfMonth();
                            }
                            else if (set_date.getDayOfMonth() < 10) {
                                end_date_text += set_date.getYear() + "/" + (set_date.getMonth() + 1) + "/" + "0" + set_date.getDayOfMonth();
                            }
                            else {
                                end_date_text += set_date.getYear() + "/" + (set_date.getMonth() + 1) + "/" + set_date.getDayOfMonth();
                            }
                            end_date.setText(end_date_text);
                            DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
                            String temp1 = start_date_text;
                            String temp2 = end_date_text;
                            try {
                                Date date1 = df.parse(temp1);
                                Date date2 = df.parse(temp2);
                                how_many_date.setText(String.valueOf((int) ((date2.getTime() - date1.getTime()) / 86400000)) + "天");
                            } catch (ParseException e) {
                                throw new RuntimeException(e);
                            }
                            dialog1.dismiss();
                        }
                    });

                    dialog1.show();
                    dialog1.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, 1500);
                    dialog1.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    dialog1.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
                    dialog1.getWindow().setGravity(Gravity.BOTTOM);
                }
            }
        });

        is_all_custom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                is_all_custom.setTextColor(Color.BLACK);
                is_just_new_custom_can_use = false;
                is_just_new_custom.setTextColor(Color.rgb(128, 128, 128));
            }
        });

        is_just_new_custom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                is_just_new_custom.setTextColor(Color.BLACK);
                is_just_new_custom_can_use = true;
                is_all_custom.setTextColor(Color.rgb(128, 128, 128));
            }
        });

        create_data.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean can_upload = true;
                for (int i = 0; i < product_data_in_choose.size(); i++) {
                    if (product_data_in_choose.get(i).after_discount_money.getText().toString().isEmpty() || Double.parseDouble(product_data_in_choose.get(i).after_discount_money.getText().toString()) >= Double.parseDouble(product_data_in_choose.get(i).product_price) || (product_data_in_choose.get(i).is_purchase_limit_in_order && product_data_in_choose.get(i).set_order_purchase_limit < 0) || (product_data_in_choose.get(i).is_purchase_limit_in_inventory && product_data_in_choose.get(i).set_inventory_purchase_limit < 0)) {
                        can_upload = false;
                        break;
                    }
                }

                if (!can_upload || start_date_text.isEmpty() || end_date_text.isEmpty() || product_data_in_choose.isEmpty()) {
                    Toast.makeText(Discount_Product_Page.this, "请输入正确资料或输入所有资料", Toast.LENGTH_SHORT).show();
                }
                else if (!is_read_and_accept.isChecked()) {
                    Toast.makeText(Discount_Product_Page.this, "请确认已阅读并同意协议", Toast.LENGTH_SHORT).show();
                }
                else {
                    set_dialog();
                    Upload_Data_Thread uploadDataThread = new Upload_Data_Thread();
                    uploadDataThread.start();
                }
            }
        });
    }

    public void set_dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater1 = LayoutInflater.from(this);
        builder.setView(inflater1.inflate(R.layout.loading, null));
        builder.setCancelable(false);

        dialog = builder.create();
        dialog.show();
    }
}